package com.lee.config;

import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.nio.Buffer;


/**
 * @Description TODO
 * @Author winston
 * @DateTime 2021/11/29
 */
@Configuration
public class AccessTokenConfig {

	@Autowired
	private RedisConnectionFactory redisConnectionFactory;

//	/**
//	 * 令牌存储, 声明token保存的位置, 内存, redis, JWT不需要保存
//	 *
//	 * @return {@link TokenStore}
//	 */
//	@Bean
//	public TokenStore tokenStore() {
//		return new InMemoryTokenStore();
//	}


//	@Bean
//	public TokenStore tokenStore() {
//		return new RedisTokenStore(redisConnectionFactory);
//	}

	@Bean
	public TokenStore tokenStore() {
		return new JwtTokenStore(jwtAccessTokenConverter());
	}

	@Bean
	public JwtAccessTokenConverter jwtAccessTokenConverter() {
		RsaSigner rsaSigner = new RsaSigner(KeyConfig.getSignerKey());
		JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
		converter.setSigner(rsaSigner);
		converter.setVerifier(new RsaVerifier(KeyConfig.getVerifierKey()));
		return converter;
	}

	@Bean
	public JWKSet jwkSet() {
		RSAKey.Builder builder = new RSAKey.Builder(KeyConfig.getVerifierKey())
				.keyUse(KeyUse.SIGNATURE)
				.algorithm(JWSAlgorithm.RS256);
		return new JWKSet(builder.build());
	}


}
